<template>
  <div class="users-container">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="可输入查询的用户名"></el-input>
        </el-form-item>
        <el-form-item :label="statusLabel">
          <el-select v-model="searchForm.status" placeholder="请选择查询的用户状态" @change="handleSearch" width="100">
            <el-option label="审核中" :value="0"></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="冻结" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="userList" border style="width: 100%">
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="realName" label="真实姓名" width="180"></el-table-column>
      <el-table-column prop="status" label="状态" >
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : scope.row.status == 0 ? 'warning' : 'danger'">
            {{ scope.row.status == 1 ? '正常' : scope.row.status == 0 ? '审核中' : '冻结' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 0"
            type="success"
            size="small"
            @click="approveUser(scope.row)"
          >
            通过
          </el-button>
          <el-button
            v-if="scope.row.status === 0"
            type="danger"
            size="small"
            @click="rejectUser(scope.row)"
          >
            拒绝
          </el-button>
          <el-button
            v-else
            :type="scope.row.status === 1 ? 'danger' : 'success'"
            size="small"
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '冻结' : '解冻' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../../api/request'

const searchForm = ref({
  username: '',
  status: '' 
})

// 计算状态标签
const statusLabel = computed(() => {
  switch (searchForm.value.status) {
    case 0:
      return '状态：审核中'
    case 1:
      return '状态：正常'
    case 2:
      return '状态：冻结'
    default:
      return '状态'
  }
})

const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const getUserList = async () => {
  try {
    const response = await request.post('/admin/user-list', {
      username: searchForm.value.username,
      status: searchForm.value.status,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (response.success) {
      userList.value = response.data.records.map(record => ({
        ...record,
        status: searchForm.value.status
      }))
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败：', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 检查是否存在审核中用户的函数
const checkPendingUsers = async () => {
  try {
    const response = await request.post('/admin/user-list', {
      status: 0, // 查询审核中状态
      pageNum: 1,
      pageSize: 1 // 只需要知道是否存在，查1条即可
    })
    return response.success && response.data.total > 0
  } catch (error) {
    console.error('检查审核中用户失败：', error)
    return false // 出错时默认不优先显示审核中
  }
}

const handleStatusChange = async (user) => {
  try {
    const newStatus = user.status === 1 ? 2 : (user.status === 2 ? 1 : 1); // 冻结变解冻，解冻变冻结，审核中通过后变正常
    const response = await request.put('/admin/modify-user-status', {
      id: user.id,
      status: newStatus
    })
    if (response.success) {
      ElMessage.success(`${user.status === 1 ? '冻结' : '解冻'}成功`)
      getUserList() // 刷新列表
    } else {
      ElMessage.error(response.message || '修改用户状态失败')
    }
  } catch (error) {
    console.error('修改用户状态失败：', error)
    ElMessage.error('修改用户状态失败')
  }
}

// 处理审核通过
const approveUser = async (user) => {
  try {
    const response = await request.put('/admin/modify-user-status', {
      id: user.id,
      status: 1 // 设置为正常状态
    })
    if (response.success) {
      ElMessage.success(`用户${user.username}审核通过`)
      getUserList() // 刷新列表
    } else {
      ElMessage.error(response.message || '审核操作失败')
    }
  } catch (error) {
    console.error('审核通过操作失败：', error)
    ElMessage.error('审核操作失败')
  }
}

// 处理审核拒绝
const rejectUser = async (user) => {
  try {
    const response = await request.put('/admin/modify-user-status', {
      id: user.id,
      status: 3 // 拒绝状态
    })
    if (response.success) {
      ElMessage.warning(`用户${user.username}审核已拒绝`)
      getUserList() // 刷新列表
    } else {
      ElMessage.error(response.message || '审核拒绝操作失败')
    }
  } catch (error) {
    console.error('审核拒绝操作失败：', error)
    ElMessage.error('审核拒绝操作失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

const resetSearch = () => {
  searchForm.value = {
    username: '',
    status: '' 
  }
  // 重置后重新执行初始化逻辑
  initializeUserList()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 页码大小改变时回到第一页
  getUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

// 初始化用户列表的逻辑
const initializeUserList = async () => {
  const hasPending = await checkPendingUsers()
  if (hasPending) {
    searchForm.value.status = 0 // 优先显示审核中
  } else {
    searchForm.value.status = 1 // 否则显示正常
  }
  getUserList() // 获取用户列表
}

onMounted(() => {
  initializeUserList() // 调用初始化函数
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>